package com.nuumoblie.bluetoothtools.bt;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.nuumobile.filepicker.controller.DialogSelectionListener;
import com.nuumoblie.bluetoothtools.BaseActivity;
import com.nuumoblie.bluetoothtools.R;

import java.io.File;

import es.dmoral.toasty.Toasty;


public class BtServerActivity extends BaseActivity implements BtOptBase.Listener, View.OnClickListener {
    private TextView mTips;
    private EditText mInputMsg;
    private EditText mInputFile;
    private TextView mLogs;
    private BtOptServer mServer;
    private Button mBtnSelectFile;
    private TextView mTvInfo;
    private CheckBox mTvBonded;

    private CheckBox mCbReListen;

    private Button mBtnListen;
    private Button mBtnCancel;

    private View mOptLayout;

    private boolean isReListen = false;

    private int recevierTimes = 0;
    private int verifyFailTimes = 0;
    private Handler mHandler = new Handler();

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_bt_server;
    }

    @Override
    public void initView() {
        mTips = findViewById(R.id.tv_tips);
        mInputMsg = findViewById(R.id.input_msg);
        mInputFile = findViewById(R.id.input_file);
        mLogs = findViewById(R.id.tv_log);
        mBtnSelectFile = findViewById(R.id.btn_file_select);
        mTvInfo = findViewById(R.id.tv_info);
        mTvBonded = findViewById(R.id.cb_bonded);
        mCbReListen = findViewById(R.id.cb_re_listen);
        mBtnCancel = findViewById(R.id.btn_cancel);
        mBtnListen = findViewById(R.id.btn_listen);
        mOptLayout = findViewById(R.id.ll_opt_layout);
        mServer = new BtOptServer(this);
    }

    @Override
    public void initEvent() {
        mBtnSelectFile.setOnClickListener(this);
        mTvBonded.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.v("lmjssjj", "isChecked:" + isChecked);
                mServer.setMatch(isChecked);
//                mHandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        mTvBonded.setEnabled(true);
//                    }
//                },3000);
//                mTvBonded.setEnabled(false);
            }
        });
        mCbReListen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isReListen = isChecked;
            }
        });
    }

    public void listen(View view) {
        if (mServer != null && !mServer.isListen()) {
            String uuid = mServer.listen();
            mTips.setText("正在监听...\n"+uuid);
            mBtnListen.setEnabled(false);
            mBtnCancel.setEnabled(true);
            mTvBonded.setEnabled(false);
        } else {
            Toasty.warning(this, "fail").show();
        }
    }

    public void cancel(View view) {
        if (mServer != null && mServer.isListen()) {
            mServer.unListen();
            mBtnCancel.setEnabled(false);
            mCbReListen.setChecked(false);
            mTvBonded.setEnabled(true);
        } else {
            Toasty.warning(this, "fail").show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mServer.unListener();
        mServer.close();
    }

    public void sendMsg(View view) {
        if (mServer.isConnected(null)) {
            String msg = mInputMsg.getText().toString();
            if (TextUtils.isEmpty(msg))
                Toasty.warning(this, "消息不能空", 0).show();
            else
                mServer.sendMsg(msg);
        } else
            Toasty.warning(this, "没有连接", 0).show();
    }

    public void sendFile(View view) {
        if (mServer.isConnected(null)) {
            String filePath = mInputFile.getText().toString();
            if (TextUtils.isEmpty(filePath) || !new File(filePath).isFile())
                Toasty.warning(this, "文件无效", 0).show();
            else
                mServer.sendFile(filePath, false);
        } else
            Toasty.warning(this, "没有连接", 0).show();
    }

    public void clearLog(View view) {
        mLogs.setText("LOG\n");
    }

    @Override
    public void socketNotify(int state, final Object obj) {
        if (isDestroyed())
            return;
        String msg = null;
        switch (state) {
            case BtOptBase.Listener.CONNECTED:
                BluetoothDevice dev = (BluetoothDevice) obj;
                msg = String.format("与%s(%s)连接成功", dev.getName(), dev.getAddress());
                mTips.setText(msg);
//                mTvBonded.setEnabled(false);
                mBtnCancel.setEnabled(true);
                break;
            case BtOptBase.Listener.DISCONNECTED:
                msg = "连接断开,请重新监听...";
                if (isReListen) {
                    mServer.listen();
                    msg = "连接断开,正重新监听...";
                } else {
                    mBtnListen.setEnabled(true);
                    mTvBonded.setEnabled(true);
                }
                mTips.setText(msg);
//                mTvBonded.setEnabled(true);
                break;
            case BtOptBase.Listener.MSG:
                msg = String.format("\n%s", obj);
                mLogs.append(msg);
                dealWithMsg(msg);
                break;
            case BtOptBase.Listener.SPEED:
                msg = String.format("%s", obj);
                mTvInfo.setText("recevierTimes:" + recevierTimes + "--  verifyFailTimes:" + verifyFailTimes + "\n" + msg);
                break;
        }
//        if (state != BtOptBase.Listener.SPEED)
//            Toasty.warning(this, msg.trim(), 0).show();
    }

    public void expand(View view) {
        if (mOptLayout.isShown()) {
            mOptLayout.setVisibility(View.GONE);
        } else {
            mOptLayout.setVisibility(View.VISIBLE);
        }
    }


    public void showInfo() {
        mTvInfo.setText("recevierTimes:" + recevierTimes + "--  verifyFailTimes:" + verifyFailTimes);
    }

    public void dealWithMsg(String msg) {
        if (msg.contains("文件接收完成")) {
            recevierTimes++;
            showInfo();
        } else if (msg.contains("校验失败")) {
            verifyFailTimes++;
            showInfo();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_file_select:
                selectFile(new DialogSelectionListener() {
                    @Override
                    public void onSelectedFilePaths(String[] files) {
                        mInputFile.setText(files[0]);
                    }
                });
                break;
        }
    }

    public void setDiscoverable3600(View view) {
        setDiscoverable();
    }

    private void setDiscoverable() {
        Intent bluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        bluetoothIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        startActivity(bluetoothIntent);
    }
}